import { createStore } from "vuex";

export default createStore({
  state: {
    shopcar: [],
  },
  mutations: {
    add(state, val) {
      // state.shopcar.push(item);

      // let res = state.shopcar.filter((item) => {
      //   return item._id == val._id;
      // });

      // if (res.length > 0) {
      //   state.shopcar.forEach((item) => {
      //     if (item._id == val._id) {
      //       item.num++;
      //     }
      //   });
      // } else {
      //   val.num = 1;
      //   state.shopcar.push(val);
      // }

      let flag = false; //代表这个商品在购物车中存不存在
      state.shopcar.forEach((item) => {
        if (item._id == val._id) {
          item.num++;
          flag = true;
        }
      });
      //必须循环结束才能知道这个商品在购物车中存不存在

      if (flag == false) {
        val.num = 1;
        val.status = false;
        state.shopcar.push(val);
      }
      //循环结束了flag都是false那就证明 这个商品不存在 往里push 并且给一个初始的num为1
    },
    del(state) {
      state.shopcar = state.shopcar.filter((item) => {
        return item.status == false;
      });
      //把不删的留下来
    },
  },
  actions: {},
  modules: {},
  getters: {
    allPrice(state) {
      let sum = 0;
      state.shopcar.forEach((item) => {
        if (item.status == true) {
          sum += item.num * item.price;
        }
      });
      return sum;
    },
  },
});
